#import "YQPSearchNewsModel.h"

#import "MYNewsBaseSearchVC.h"
#import "YQNavTitleView.h"
#import "YQSearchBaseBar.h"
#import "MYShopSearchScreenHeader.h"
#import "MYShopSearchGoodsCell.h"
#import "MYShopSearchScreenView.h"
#import "YQPAdvisorySelectTypeView.h"
#import "MYNewsModel.h"
#import "MYShopSearchScreenView.h"
#import "MYNewsBaseScreenModel.h"
@interface MYNewsBaseSearchVC ()<YQSearchBaseBarDelegate,UITableViewDelegate,UITableViewDataSource,MYShopSearchScreenViewDelegate>
@property (nonatomic, strong) MYShopSearchScreenView *screenView ;
@property (nonatomic, strong) YQSearchBaseBar * searchBar;

@property (nonatomic, strong) YQPAdvisorySelectTypeView * saleTypeView;

@property (nonatomic, strong) YQPAdvisorySelectTypeView * selctTypeView;

//右边筛选View
@property (strong, nonatomic) MYShopSearchScreenView *searchView;

@property (nonatomic, copy) NSArray * sortTitleArr;
@property (nonatomic, copy) NSString * synthesizeSelectStr;

@property (nonatomic, strong) NSMutableDictionary * filterDic;

/// 升降序 销量排序方式：asc->升序 desc->降序
@property (nonatomic, copy) NSString *saleSortStr;

@property (nonatomic, copy) NSArray * saleTitleArr;

/// 升降序 价格排序方式：asc->升序 desc->降序
@property (nonatomic, copy) NSString *priceSortStr;

@property (nonatomic, strong) YQPAdvisorySelectTypeView * selctPriceTypeView;

@property (strong, nonatomic) NSMutableArray *brandIds;

@property (nonatomic, copy) NSString *selectID;

@property (nonatomic, copy) NSString *minPrice;

@property (nonatomic, copy) NSString *maxPrice;

@end

@implementation MYNewsBaseSearchVC


- (MYShopSearchScreenView *)searchView
{
    if (!_searchView) {
        _searchView = [[MYShopSearchScreenView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _searchView.catalog3Id = self.selectID;
        _searchView.delegate = self;
    }
    return _searchView;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    self.synthesizeSelectStr = kYQLS(@"综合");
    self.sortTitleArr = @[kYQLS(@"综合"),kYQLS(@"最新"),kYQLS(@"热门")];
    self.saleTitleArr = @[kYQLS(@"降序"),kYQLS(@"升序")];
    self.dataArr = NSMutableArray.new;
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //销毁筛选弹框
    [self.selctTypeView cancelSelctTableView];
    [self.saleTypeView cancelSelctTableView];

}
-(void)setupView {
    [super setupView];
    
    YQNavTitleView *navView = [YQNavTitleView new];
    navView.frame = CGRectMake(46, 0, kScreenWidth-100, 44);
    navView.intrinsicContentSize = CGSizeMake(kScreenWidth-100, 44);
    self.navigationItem.titleView = navView;
    
    UIView *bgView = [UIView new];
    navView.backgroundColor = UIColor.whiteColor;
    [navView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [bgView addSubview:self.searchBar];
    [self.view addSubview:self.listTableView];
    [self setupRefresh:self.listTableView];
    [self onStartRefresh];
}

- (void)onStartRefresh {
    self.page = 1;
    [self getNewList];
}

- (void)onStartLoadMore {
    self.page ++;
    [self getNewList];
}

-(void)getNewList {
    YQSHOWLOADINGTIPS(@"")
    self.filterDic[@"pageNo"] = @(self.page);
    self.filterDic[@"salesVolumeSort"] = self.saleSortStr;// (string, optional): 销量排序方式：asc->升序 desc->降序 ,
    ws(self);
    [YQPNetWorkingManager sendPostRequest:kPOST_INFORMATION_FILTER_LIST_URL parameters:self.filterDic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        [weakself stopRefresh];
        if (responseObject.code == 0) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
            }
            NSArray *arr = [NSArray modelArrayWithClass:[MYNewsModel class] json:responseObject.data[@"list"]];
            [self.dataArr addObjectsFromArray:arr];
            [self.listTableView reloadData];
            if (arr.count == 0) {
                [self.listTableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        [weakself stopRefresh];
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error)
    }];

}

-(void)leftItemAction:(UIButton *)sneder {
    [self.selctTypeView cancelSelctTableView];
    [super leftItemAction:sneder];
}

#pragma makr -- YQSearchBaseBarDelegate
- (void)yq_searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.filterDic[@"keyword"] = searchBar.text;
    [self onStartRefresh];
}
-(void)yq_textFieldShouldClear:(UITextField *)textField {
    
}
-(void)yq_shouldChangeText:(NSString *)text {
    self.filterDic[@"keyword"] = text;
    [self onStartRefresh];
}
#pragma makr -- YQSearchBaseBarDelegate end


#pragma mark - UITableViewDelegate, UITableViewDataSource
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self.view endEditing:true];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MYShopSearchGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSearchGoodsCell"];
    cell.titleLb.text = @"子初(Springbuds)母婴本色抽纸婴儿抽取式面巾纸家用纸";
    cell.priceLb.text = @"$1599.00";
    cell.payCountLb.text = @"2.7万人付款 付款";
//    MYNewsGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYNewsGoodsCell"];
//    MYNewsModel *newsModel = nil;
//    if (indexPath.row < self.dataArr.count) {
//        newsModel = self.dataArr[indexPath.row];
//    }
//
//    cell.newsModel = newsModel;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 112;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MYShopSearchScreenHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MYShopSearchScreenHeader"];
    
    [header.synthesizeBtn addTarget:self action:@selector(synthesizeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [header.synthesizeBtn setTitle:self.synthesizeSelectStr forState:(UIControlStateNormal)];
    [header.sellBtn addTarget:self action:@selector(sellAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [header.screenBtn addTarget:self action:@selector(screenAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.screenHeaderView = header;
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma mark -- heaer Action
-(void)synthesizeAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.selctTypeView showSelctTableView];
    } else {
        [self.selctTypeView cancelSelctTableView];
    }
    
}

#pragma mark - 销量筛选功能
-(void)sellAction:(UIButton *)sender {

    sender.selected = !sender.selected;
        if (!sender.selected) {
            self.saleSortStr = @"desc";
        }else {
            self.saleSortStr = @"asc";
        }
        //根据价格排序刷新接口
//        [self getUserSearchNewsSortsApi:YES];
        if (sender.selected) {
            [self.saleTypeView showSelctTableView];
        } else {
            [self.saleTypeView cancelSelctTableView];
        }
}

#pragma mark - 销量排序
-(YQPAdvisorySelectTypeView *)saleTypeView {
    if (!_saleTypeView) {
        ws(self);
        _saleTypeView = [[YQPAdvisorySelectTypeView alloc] initWithFrame:CGRectMake(0, Height_NavBar+44, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) dataSource:self.saleTitleArr.copy selectStr:self.synthesizeSelectStr resultBlack:^(NSString * _Nonnull result, NSInteger index) {
            
            if ([result isEqualToString:kYQLS(@"降序")]) {
                self.saleSortStr = @"desc";
            }else if ([result isEqualToString:kYQLS(@"升序")]) {
                self.saleSortStr = @"asc";
            }
            
            self.synthesizeSelectStr = result;
            //根据价格排序刷新接口
//            [self getUserSearchNewsSortsApi:YES];
            [self onStartRefresh];
            [self.screenHeaderView.sellBtn setTitle:result forState:(UIControlStateSelected)];
//            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        } cancelBlack:^{
//            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        }];
    }
    return _saleTypeView;
}

#pragma mark - 按照查询条件分页查询---三级资讯查询
- (void)getUserSearchNewsSortsApi:(BOOL)isReload
{
    if (isReload) {
        self.page = 1;
    }
    NSMutableDictionary *dic = NSMutableDictionary.new;

    dic[@"attrValueList"] = self.brandIds;// (Array[APP端搜索参数接收], optional): 平台属性参数接收 ,
    dic[@"catalog3Id"] = self.selectID;// (string, optional): 三级分类ID ,
    dic[@"keyword"] = self.searchBar.searchBar.text;// (string, optional): 搜索关键字 ,
    dic[@"limit"] = @(10);// (integer, optional): 每页大小：默认为10 ,
    dic[@"pageNo"] = @(self.page);// (integer, optional): 当前页码：默认为1 ,
    dic[@"priceSort"] = self.priceSortStr;// (string, optional): 价格排序方式：asc->升序 desc->降序 ,
    dic[@"salesVolumeSort"] = self.saleSortStr;// (string, optional): 销量排序方式：asc->升序 desc->降序 ,
    dic[@"endPrice"] = self.maxPrice.length >0?self.maxPrice:nil;// (number, optional): 结束价格区间 ,
    dic[@"startPrice"] = self.minPrice.length >0?self.minPrice:nil;// (number, optional): 开始价格区间
    
    YQSHOWLOADINGTIPS(kYQLS(@"加载中"))
    [YQPNetWorkingManager sendPostRequest:kPOST_SEARCH_APPLIST_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (self.page == 1) {
            [self.dataArr removeAllObjects];
        }
        YQPSearchNewsModel *model = [YQPSearchNewsModel mj_objectWithKeyValues:responseObject.data];
        [self.dataArr addObjectsFromArray:model.list];
        
        if (!self.selectID) {
            self.listTableView.hidden = (self.dataArr.count == 0);
            if (self.dataArr.count == 0 && ([self.searchBar.searchBar.text removeStringSpace].length != 0)) {
                kMBMesHUD(kYQLS(@"未查询到相关商品"));
            }
        }
        YQPNewsEntityModel *entityModel = self.dataArr.firstObject;
        if (!self.selectID) {
            self.searchView.catalog3Id = entityModel.catalog3Id;
        }
        
        [self.listTableView reloadData];
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
        if(self.page == model.totalPage.integerValue) {
            [self.listTableView.mj_footer endRefreshingWithNoMoreData];
        }

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
    }];
}


#pragma mark - 价格排序
-(YQPAdvisorySelectTypeView *)selctPriceTypeView {
    if (!_selctPriceTypeView) {
        ws(self);
        _selctPriceTypeView = [[YQPAdvisorySelectTypeView alloc] initWithFrame:CGRectMake(0, Height_NavBar+44, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) dataSource:self.sortTitleArr.copy selectStr:self.synthesizeSelectStr resultBlack:^(NSString * _Nonnull result, NSInteger index) {
            self.synthesizeSelectStr = result;
            if ([result isEqualToString:kYQLS(@"综合")]) {
                self.priceSortStr = @"";
            }else if ([result isEqualToString:kYQLS(@"价格降序")]) {
                self.priceSortStr = @"desc";
            }else if ([result isEqualToString:kYQLS(@"价格升序")]) {
                self.priceSortStr = @"asc";
            }
            //根据价格排序刷新接口
            [self getUserSearchNewsSortsApi:YES];
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [self.screenHeaderView.synthesizeBtn setTitle:result forState:(UIControlStateNormal)];
//            self.screenHeaderView.synthesizeBtn.selected = YES;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
        } cancelBlack:^{
//            self.screenHeaderView.synthesizeBtn.selected = NO;
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctPriceTypeView removeFromSuperview];
            weakself.selctPriceTypeView = nil;
            [self.screenHeaderView setSynthString:self.synthesizeSelectStr];

        }];
    }
    return _selctPriceTypeView;
}

#pragma mark - 侧拉屏幕
-(void)screenAction:(UIButton *)sender {
    [self.selctTypeView cancelSelctTableView];
    [self.screenView showSelctTableView];
}
#pragma mark -- heaer Action end;
#pragma mark --MYShopSearchScreenViewDelegate
- (void)didSelectGoodItemGetBrandIds:(NSArray *)subBrandIds andMinPrice:(NSString *)minPrice andMaxPrice:(NSString *)maxPrice
{
//    self.filterDic[@"informationSearchAttrList"] = subBrandIds;
    self.filterDic[@"informationValueIds"] = subBrandIds;
    [self onStartRefresh];
}
#pragma mark --MYShopSearchScreenViewDelegate end
#pragma mark -- lazy
-(YQSearchBaseBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[YQSearchBaseBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 100, 28)];
        _searchBar.top = 11;
        _searchBar.delegate = self;
        _searchBar.placeholderStr = kYQLS(@"搜索您想要的物品");
    }
    return _searchBar;
}


- (YQBaseTableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[YQBaseTableView alloc] initWithFrame:CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea) style:UITableViewStylePlain];
        _listTableView.backgroundColor = UIColor.whiteColor;
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        [_listTableView registerNib:[UINib nibWithNibName:@"MYShopSearchScreenHeader" bundle:nil] forHeaderFooterViewReuseIdentifier:@"MYShopSearchScreenHeader"];
        [_listTableView registerNib:[UINib nibWithNibName:@"MYShopSearchGoodsCell" bundle:nil] forCellReuseIdentifier:@"MYShopSearchGoodsCell"];
        [_listTableView registerNib:[UINib nibWithNibName:@"MYNewsGoodsCell" bundle:nil] forCellReuseIdentifier:@"MYNewsGoodsCell"];
    }
    return _listTableView;
}


-(YQPAdvisorySelectTypeView *)selctTypeView {
    if (!_selctTypeView) {
        ws(self);
        _selctTypeView = [[YQPAdvisorySelectTypeView alloc] initWithFrame:CGRectMake(0, 108, kYQPScreenWidth, kYQPScreenHeight-108-kHeight_Botton_SafeArea) dataSource:self.sortTitleArr.copy selectStr:self.synthesizeSelectStr resultBlack:^(NSString * _Nonnull result, NSInteger index) {
            NSString *synthesize = index == 0 ? @"" : [NSString stringWithFormat:@"%zd",index-1];
            self.filterDic[@"synthesize"] = synthesize;
            [self.screenHeaderView.synthesizeBtn setTitle:result forState:(UIControlStateNormal)];
            self.synthesizeSelectStr = result;
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctTypeView removeFromSuperview];
            weakself.selctTypeView = nil;
            [self getNewList];
        } cancelBlack:^{
            self.screenHeaderView.synthesizeBtn.selected = NO;
            [weakself.selctTypeView removeFromSuperview];
            weakself.selctTypeView = nil;
        }];
    }
    return _selctTypeView;
}

-(NSMutableDictionary *)filterDic {
    if (!_filterDic) {
        _filterDic = [NSMutableDictionary dictionary];
        //默认
        _filterDic[@"informationCategoryId"] = self.categoryId;
        _filterDic[@"informationValueIds"] = @[];
        _filterDic[@"city"] = @"";//[Config currentConfig].city;
        _filterDic[@"limit"] = @"10";
        _filterDic[@"keyword"] = @"";
        _filterDic[@"synthesize"] = @"";
        _filterDic[@"latitude"] = [Config currentConfig].latitude;
        _filterDic[@"longitude"] = [Config currentConfig].longitude;
        
    }
    return _filterDic;
}

- (MYShopSearchScreenView *)screenView
{
    if (!_screenView) {
        _screenView = [[MYShopSearchScreenView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _screenView.isNewsScreen = YES;
        _screenView.catalog3Id = self.categoryId;//[NSString stringWithFormat:@"%zd",self.categoryId];
        _screenView.delegate = self;
    }
    return _screenView;
}

#pragma mark -- lazy end
-(void)stopRefresh {
    [self.listTableView.mj_header endRefreshing];
    [self.listTableView.mj_footer endRefreshing];
}
@end
